<?php
// .-----------------------------------------------------------------------------------
// | WE TRY THE BEST WAY 杭州博也网络科技有限公司
// |-----------------------------------------------------------------------------------
// | Author: 吃草的鱼 <783188184@qq.com>
// | Copyright (c) 2016-2018, http://www.itboye.com. All Rights Reserved.
// |-----------------------------------------------------------------------------------

namespace Home\Controller;
use Shop\Api\ProductSkuApi;
use Think\Controller;
use Shop\Api\CategoryApi;
use Shop\Api\ProductApi;
use Shop\Api\OrdersExpressApi;
use Shop\Api\ProductImageApi;
use Weixin\Api\WxuserApi;
use Admin\Api\UserPictureApi;
use Shop\Api\AddressApi;
use Shop\Api\OrdersApi;
use Shop\Api\OrdersItemApi;
use Shop\Api\OrderRefundMoneyApi;
use Shop\Api\OrdersContactInfoApi;
use Weixin\Api\WxaccountApi;
use Common\Api\WeixinApi;

class MybuysellController extends HomeController {

    /*
     * 卖出的商品列表详情
     * */
    public function mysell(){
        //需要连表查询
        $ordermap['a.uid'] = $this->userinfo['uid'];
        $ordermap['o.status'] = 1;
        $sellinfo = apiCall(ProductApi::SELECT_SELL_ORDER,array($ordermap,'a.id,a.name,i.img,i.price,o.pay_status,o.order_status,o.uid,o.order_code'));
        if($sellinfo['status']){
            if(!is_null($sellinfo['info'])) {
                $refundres = apiCall(OrderRefundMoneyApi::QUERY_NO_PAGING);
                if($refundres['status']){
                    $this->assign('refund',$refundres['info']);
                }
                //将所有订单编号拿出来
                foreach ($sellinfo['info'] as $vo) {
                    $order_code[] = $vo['order_code'];
                }
                $order_code_str = implode(',', $order_code);
                //进行物流单号查询
                $order_codemap['order_code'] = array('in', $order_code_str);
                $orderinfo = apiCall(OrdersExpressApi::QUERY_NO_PAGING, array($order_codemap));
                if ($orderinfo['status']) {
                    $this->assign('orderinfo', $orderinfo['info']);
                    $this->assign('sellinfo', $sellinfo['info']);
                    $this->display();
                } else {
                    $this->error('对不住 物流单号查询失败');
                }
            }else{
                $this->display();
            }
        }else{
            $this->error('抱歉出错了');
        }
    }

    /*
     * 卖出的商品的详细情况
     * */
    public function selldetail(){
        //详情进来你会带上订单编号
        $map['c.order_code'] = I('order_code');
        $express_contactinfo = apiCall(OrdersExpressApi::GET_EXPRESS_CONTACT,array($map));//与orders_contactinfo表相连接获取了收货地址和宝贝详情
        if($express_contactinfo['status']){
            $ordermap['order_code'] = $map['c.order_code'];
            $iteminfo = apiCall(OrdersItemApi::GET_INFO,array($ordermap));//获取订单item中的相关信息
            if($iteminfo['status']){
                //将所有退款信息拿出
                $refundres = apiCall(OrderRefundMoneyApi::QUERY_NO_PAGING);
                if($refundres['status']){
                    $this->assign('refund',$refundres['info']);
                }
                //为了确认订单是否收货还需要orders表中的数据
                $orderinfo = apiCall(OrdersApi::GET_INFO,array($ordermap));//获取订单order中的order_status
                //拿到卖家信息
                if($orderinfo['status']){
                    $wxusermap['id'] = $orderinfo['info']['uid'];
                    $wxuserinfo = apiCall(WxuserApi::GET_INFO,array($wxusermap));
                    if($wxuserinfo['status']){
                        $this->assign('nickname',$wxuserinfo['info']['nickname']);
                    }
                }

                $this->assign('express_contactinfo',$express_contactinfo['info']);
                $iteminfo['info']['sumprice'] = $iteminfo['info']['price'] + $iteminfo['info']['post_price'];
                $this->assign('iteminfo',$iteminfo['info']);
                $this->assign('pay_status',$orderinfo['info']['pay_status']);//支付状态
                $this->assign('order_status',$orderinfo['info']['order_status']);//订单状态
                $this->display();
            }else{
                $this->error('不好意思出错了');
            }
        }else{
            $this->error('不好意思出错了');
        }
    }

    /*
     * 我要发货 以及发货信息上传
     * */
    public function send_good(){
        if(IS_POST){
            $express['expresscode'] = I('expresscode');//快递公司编码
            $express['expressname'] = I('expressname');//快递公司名称
            $express['expressno'] = I('expressno');//快递单号
            if(empty($express['expressname']) || empty($express['expressno'])){
                $this->error('嘿嘿 真粗心 您忘填写快递公司名称或者单号了');
            }
            $express['order_code'] = I('order_code');//订单编号
            $express['uid'] = I('uid');//下单用户的ID
            $express['createtime'] = time();
            $express['updatetime'] = time();
            //将用户信息存入
            $expressres = apiCall(OrdersExpressApi::ADD,array($express));
            if($expressres['status']){
                //添加成功后要orders表的中的订单状态进行改变
                $ordermap['order_code'] = $express['order_code'];
                $order['order_status'] = 4;//表示已经发货
                $orders = apiCall(OrdersApi::SAVE ,array($ordermap, $order));
                if($orders['status']){
                    $this->success('发货信息上传成功');
                }else{
                    $this->error('发货信息上传失败');
                }
            }else{
                $this->error('发货信息上传失败');
            }

        }else{
            $this->assign('order_code',I('order_code'));
            $this->assign('uid',I('uid'));//下单用户的ids
            $this->display();
        }
    }

    /*
     *在卖家没有发货的时候买家取消了订单 申请退款  卖家主动进行确认退款
     * */
    public function confirm_refund(){
        $order_code = I('order_code','');
        if(!empty($order_code)){
            $model = M();
            $model->startTrans();//开启事务
            $flag = false;
            $map['order_code'] = $order_code;
            $save['result'] = 1;
            $orderitemres = apiCall(OrdersItemApi::GET_INFO,array($map));
            if($orderitemres['status']){
                $skumap['product_id'] = $orderitemres['info']['p_id'];
                $producnumberres = apiCall(ProductSkuApi::GET_INFO,array($skumap));
                if($producnumberres['status']){
                    $skusave['quantity'] = $producnumberres['info']['quantity']+$orderitemres['info']['count'];
                    $skures = apiCall(ProductSkuApi::SAVE,array($skumap,$skusave));
                }
            }

            $redundres = apiCall(OrderRefundMoneyApi::SAVE,array($map,$save));
            if($redundres['status']){
                //调出下单用户的uid
                $orderinfo = apiCall(OrdersApi::GET_INFO,array($map));
                if($orderinfo['status']){
                    $wxuserid['id'] = $orderinfo['info']['uid'];
                    $momeyinfo = apiCall(WxuserApi::GET_INFO,array($wxuserid));
                    if($momeyinfo['status']){
                        $xsave['money'] = bcadd($momeyinfo['info']['money'],bcadd($orderinfo['info']['price'],$orderinfo['info']['post_price'],2),2);
                        $orderinfo = apiCall(WxuserApi::SAVE,array($wxuserid,$xsave));
                        if(!$orderinfo['status']){
                            $false = true;
                        }
                    }else{
                        $flag = true;
                    }
                }else{
                    $flag = true;
                }
            }else{
               $flag = true;
            }
            if ($flag) {
                $model->rollback();
                echo false;
            } else {
                $model->commit();
                echo true;
            }
        }else{
            echo false;
        }
    }

    /*
    * 买到的商品列表详情
    * */
    public function mybuy(){
        $ordermap['o.uid'] = $this->userinfo['uid'];
        $ordermap['o.status'] = 1;
        $buyinfo = apiCall(OrdersApi::SELECT_SELL_ORDER,array($ordermap,'i.name,i.img,i.price,i.p_id,o.pay_status,o.order_status,o.uid,o.order_code,o.grouptype,o.counttype'));

        if($buyinfo['status']){
            if(!is_null($buyinfo['info'])) {
                //将所有订单编号拿出来
                foreach ($buyinfo['info'] as $vo) {
                    $order_code[] = $vo['order_code'];
                }
                $order_code_str = implode(',', $order_code);
                //进行物流单号查询
                $order_codemap['order_code'] = array('in', $order_code_str);
                $orderinfo = apiCall(OrdersExpressApi::QUERY_NO_PAGING, array($order_codemap));
                if ($orderinfo['status']) {
                    $this->assign('orderinfo', $orderinfo['info']);
                    $this->assign('buyinfo', $buyinfo['info']);

                    $this->display();
                } else {
                    $this->error('对不住 物流单号查询失败');
                }
            }else{
                $this->display();
            }
        }else{
            $this->error('抱歉出错了');
        }
    }

    /*
     * 买到的商品的详细情况
     * */
    public function buydetail(){
        //详情进来你会带上订单编号
        $map['c.order_code'] = I('order_code');
        //连表查出卖家昵称
        $orderitemmap['itboye_orders_item.order_code'] = $map['c.order_code'];
        $wxuser = apiCall(OrdersItemApi::ORDEPX,array($orderitemmap,'itboye_wxuser.nickname'));
        if($wxuser['status']){
            $this->assign('nickname',$wxuser['info']['nickname']);
        }

        $express_contactinfo = apiCall(OrdersExpressApi::GET_EXPRESS_CONTACT,array($map));//与orders_contactinfo表相连接获取了收货地址和宝贝详情
        if($express_contactinfo['status']){
            $ordermap['order_code'] = $map['c.order_code'];
            $iteminfo = apiCall(OrdersItemApi::GET_INFO,array($ordermap));//获取订单item中的相关信息
            if($iteminfo['status']){
                //为了确认订单是否收货还需要orders表中的数据
                $orderinfo = apiCall(OrdersApi::GET_INFO,array($ordermap));//获取订单order中的order_status

                $this->assign('express',$express_contactinfo['info']);
                $iteminfo['info']['sumprice'] = $iteminfo['info']['price'] + $iteminfo['info']['post_price'];//计算总价
                $this->assign('iteminfo',$iteminfo['info']);
                $this->assign('order_status',$orderinfo['info']['order_status']);
                $this->assign('pay_status',$orderinfo['info']['pay_status']);
                $this->display();
            }else{
                $this->error('不好意思出错了');
            }
        }else{
            $this->error('不好意思出错了');
        }
    }

    /*
     * 主动确认收货
     * */
    public function confirm_receipt(){
        if(!empty(I('order_code'))) {
            $map['order_code'] = I('order_code');
            $save['order_status'] = 5;//表示已经收货
            $model = M();
            $model->startTrans();//开启事务
            $flag = false;
            $result = apiCall(OrdersApi::SAVE, array($map, $save));
            if (!$result['status']) {
                $flag = true;
            } else {
                //找到卖家信息存入钱
                $result = apiCall(OrdersItemApi::ORDEPX, array(array('itboye_orders_item.order_code' => $map['order_code']), false, 'itboye_orders_item.order_code,itboye_orders_item.price,itboye_orders_item.post_price,itboye_wxuser.id,itboye_wxuser.money'));
                $wxusermap['id'] = $result['info']['id'];
                $moneysave['money'] = $result['info']['money'] + $result['info']['price'] + $result['info']['post_price'];
                $accountres = apiCall(WxuserApi::SAVE, array($wxusermap, $moneysave));
                if (!$accountres['status']) {
                    $flag = true;
                }
            }
            if ($flag) {
                $model->rollback();
                echo false;
            } else {
                $model->commit();
                echo true;
            }
        }else{
            echo false;
        }
    }
    /*
   * 在没发货时向买家申请退款
   * */
    public function apply_returnmoney()
    {
        $result = apiCall(WxaccountApi::GET_INFO, array(array('id' => 5)));
        if ($result['status'] && is_array($result['info'])) {
            $this->wxaccount = $result['info'];
            $this->wxapi = new WeixinApi($this->wxaccount['appid'], $this->wxaccount['appsecret']);
        } else {
            exit("公众号信息获取失败，请重试！");
        }
        $model = M();
        $model->startTrans();//开启事务
        $flag = false;
        $order_code = I('order_code');
        $map['order_code'] = $order_code;
        $save['order_status'] = 8;
        $saveres = apiCall(OrdersApi::SAVE,array($map,$save));
        if(!$saveres['status']){
            $flag = true;
        }else{
            //获得商品卖家信息
            $result = apiCall(OrdersItemApi::ORDEPX, array(array('itboye_orders_item.order_code' => $order_code), false, 'itboye_orders_item.order_code,itboye_orders_item.price,itboye_orders_item.post_price,itboye_wxuser.openid'));
            if ($result['status']) {
                //将退款申请放入orders_refund_money表中待退款使用
                $adddata['order_code'] = $order_code;
                $adddata['reason'] = "买家在没发货前主动提出退款";
                $adddata['create_time'] = time();
                $adddata['result'] = 2;//表是等待卖家确认
                $adddata['money'] = ($result['info']['price']+$result['info']['post_price']);
                $redundres = apiCall(OrderRefundMoneyApi::ADD,array($adddata));
                if(!$redundres['status']){
                    $flag = true;
                }else{
                    //微信通知数据
                    $data['touser'] = $result['info']['openid'];
                    $data['template_id'] = "Jje65Y3DHMG0ky_7M_dZtXPfOGizPfg7w-b0XNSkFKE";
                    $data['url'] = "http://weixin.qq.com/download";
                    $data['data']['first']['value'] = "买家申请终止订单退款";
                    $data['data']['first']['color'] = "#173177";
                    $data['data']['keyword1']['value'] = $map['order_code'];//订单编号
                    $data['data']['keyword1']['color'] = "#173177";
                    $data['data']['keyword2']['value'] = "买家主动取消订单";
                    $data['data']['keyword2']['color'] = "#173177";
                    $data['data']['remark']['value'] = "希望您前往个人中心确认 不然在10天后系统会自动进行退款";
                    $data['data']['remark']['color'] = "#173177";
                    $spendres =  $this -> wxapi-> sendTmplMsgToFans($data);
                }
            }
           if($spendres['errcode'] == 0 && !$flag){
               $model->commit();
               echo true;
           }else{
               $model->rollback();
                echo false;
           }
        }
    }

}